<?php

namespace App\Http\Controllers\Guard\Login;

use App\Http\Controllers\Common\GuardController;
use App\Models\Common\China;
use App\Models\Rbac\GuardUser;
use App\Models\Rbac\LoginLog;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginController extends GuardController
{
    public function login(Request $request) {

        $from = $request->header('from','guard');
        $adminUserName = $request->input('adminUserName');
        $password = $request->input('password');
        $adminUser = (new GuardUser())->getAdminUserByNameAndPwd($adminUserName,md5($password));
        if(!empty($adminUser)){
            $adminUser->token = createNewToken($adminUser->id,$from);
            if(env('IS_WRITE_LOGIN_LOG',false))
                $adminUser->addLoginLog($request->ip(),getOS(),getBrowser());

            if(env('IS_USE_REDIS',false)){
                $key = "token:$from:$adminUser->token";
                if(!Redis::exists($key)){
                    Redis::setex("token:$from",env('TOKEN_LIFE_TIME',120),$adminUser->token);
                }
            }

            return responseSuccess($adminUser->toArray(),1,200000);
        }else{
            return responseFail(200001);
        }
    }

    public function logout(Request $request) {
        $from = $request->header('from');
        $token = $request->header('token');

        if(env('IS_USE_REDIS',false)){
            $key = "token:$from:$token";
            if(Redis::exists($key)){
                Redis::del($key);
            }
        }

        return responseSuccess([],0,200002);
    }

    public function getVerifyCodeImg(Request $request) {
        $w = $request->input('w',150);
        $h = $request->input('h',50);
        $builder  = new CaptchaBuilder();
        $builder->build($w,$h);
        $phrase = $builder->getPhrase();//获取验证码内容
        $request->session()->put('verifyCode',$phrase);
        ob_clean();
        return response($builder->output())->header('Content-type','image/jpeg');
    }

    public function getArea(Request $request) {
        $records = China::where('pcode',0)->with('children')->get();
        $this->handleChildren($records);
        return responseSuccess($records->toArray());
    }
}
